import React, { useState } from 'react';
import { history } from 'umi';
import {
  Form,
  Input,
  Button,
  message,
  Radio,
  Row,
  Col,
  Checkbox,
  Spin,
} from 'antd';
import {
  UserOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import './index.less';
import { loginUser, onLogin } from './cookie';
import request from '../../http';
import SecurityService, { RemembePassword } from './service';
import logo_1 from '@/images/logo_1.png';
import PasswordEdit from './passwordEdit';
import { PasswordEditObject } from '@/pages/login/passwordEdit';

export default function index() {
  const [
    currentEditObject,
    setCurrentEditObject,
  ] = React.useState<PasswordEditObject>({
    isModalVisible: false,
  });
  const formItemLayout = {
    wrapperCol: {
      span: 18,
      offset: 3,
    },
    labelCol: {
      span: 18,
      offset: 3,
    },
  };

  const Pagejump = () => {
    GetcheckCode();
    formObject.resetFields();
  };

  const [formObject] = Form.useForm(); //获取数据

  const onFinish = async (values: any) => {
    await request
      .post(
        '/api/auth/login',
        { ...values, checkId: checkCodeId },
        { headers: { 'Content-Type': 'application/json' } },
      )
      .then((response: any) => {
        if (response.code == '200') {
          onLogin({
            role: value,
            userNo: values.userNo,
            name: response.data.name,
          });
          if (values.remember) {
            RemembePassword.savePassword({
              Y: values.userNo,
              X: values.password,
            });
          } else {
            RemembePassword.savePassword({
              Y: values.userNo,
              password: '',
            });
          }
          SecurityService.saveSecurity(response.data.token);
          if (response.data.isFirstLogin == 0) {
            if (loginUser().role == '1') {
              history.push('/student/info/team');
            } else if (loginUser().role == '2') {
              history.push('/teacher/course');
            } else {
              history.push('/admin/studentInfo/index');
            }
          } else {
            setCurrentEditObject({
              isModalVisible: true,
              old_password: values.password,
            });
          }
        } else {
          message.error(response.message);
        }
      });
  };

  const GetPassword = () => {
    formObject.setFieldsValue({
      userNo:
        RemembePassword.getPassword() == null
          ? ''
          : RemembePassword.getPassword().Y,
      password:
        RemembePassword.getPassword() == null
          ? ''
          : RemembePassword.getPassword().X,
    });
  };

  const [checkCode, setcheckCode] = useState<any>();
  const [checkCodeId, setcheckCodeId] = useState();

  const GetcheckCode = async () => {
    await request
      .get('/api/auth/getCode', { responseType: 'arraybuffer' })
      .then((response: any) => {
        setcheckCodeId(response.headers.token);
        setcheckCode(
          'data:image/png;base64,' +
            btoa(
              new Uint8Array(response.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                '',
              ),
            ),
        );
      });
  };

  React.useEffect(() => {
    GetPassword();
    GetcheckCode();
  }, []);

  const [value, setValue] = React.useState('1');

  const onChange = (e: any) => {
    setValue(e.target.value);
  };
  const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
  return (
    <div id="login" style={{ minWidth: 1200, minHeight: 800 }}>
      <Row justify="center">
        <Col span={24} id="ant-row_1"></Col>
        <Col id="ant-row_2_1" span={7} offset={11}>
          <Col span={12} offset={2} style={{ marginTop: 35 }}>
            <img src={logo_1} />
          </Col>
          <Col span={18} offset={3}>
            <h2>学生实训考勤管理系统</h2>
          </Col>
          <Col span={24} offset={2}>
            <Form
              {...formItemLayout}
              name="normal_login"
              className="login-form"
              initialValues={{ roleType: '1', remember: true }}
              onFinish={onFinish}
              form={formObject}
            >
              <Form.Item
                name="userNo"
                rules={[{ required: true, message: '请输入你的账号!' }]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="账号"
                />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入你的密码!' }]}
              >
                <Input.Password
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  placeholder="密码"
                />
              </Form.Item>

              <Form.Item
                name="checkCode"
                rules={[{ required: true, message: '请输入验证码!' }]}
              >
                <Row>
                  <Col span={17}>
                    <Input
                      prefix={
                        <SafetyCertificateOutlined className="site-form-item-icon" />
                      }
                      placeholder="验证码"
                    />
                  </Col>
                  <Col span={7} style={{ textAlign: 'center' }}>
                    {checkCode == undefined ? (
                      <Spin indicator={antIcon} />
                    ) : (
                      <img
                        id="checkCode"
                        onClick={GetcheckCode}
                        src={checkCode}
                      ></img>
                    )}
                  </Col>
                </Row>
              </Form.Item>
              <Form.Item name="roleType">
                <Radio.Group onChange={onChange} value={value}>
                  <Radio value={'1'}>学生</Radio>
                  <Radio value={'2'}>教师</Radio>
                  <Radio value={'0'}>管理员</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item>
                <Form.Item name="remember" valuePropName="checked" noStyle>
                  <Checkbox>记住密码</Checkbox>
                </Form.Item>
                <a
                  className="login-form-forgot"
                  href="#"
                  onClick={() => {
                    message.error('请联系管理员');
                  }}
                >
                  忘记密码
                </a>
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" id="loginButton">
                  登录
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Col>
        <Col style={{ marginTop: '6vh' }}>
          <p>
            Copyright 重庆工程学院 版权所有 渝ICP备09014106 渝公网安备
            50011302000724号(建议使用IE9以上浏览器)
          </p>
        </Col>
      </Row>
      <PasswordEdit
        editObject={currentEditObject}
        Pagejump={Pagejump}
      ></PasswordEdit>
    </div>
  );
}
